package database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.JOptionPane;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


public class Writing {
	private static String fileName;
	private static Document document;
	private static Element root;
	static SAXBuilder builder;
	
	public Writing(String _fileName){
		fileName=_fileName;
		builder = new SAXBuilder();
	}
	
	public void writeNewFragment(Fragment fgt) {
		 try {
				document = builder.build(fileName);
				root = document.getRootElement();
				//fragment
				Element newFragment = new Element("fragment");
				newFragment.setAttribute("name", fgt.getName());
				newFragment.setAttribute("process", fgt.getProcess());
				newFragment.setAttribute("position", fgt.getPosition());
				//elements
				HashMap<String, ArrayList<Operation>> elts= new HashMap<String, ArrayList<Operation>>();
				elts.putAll(fgt.getElementList());
				Set nameElts = elts.keySet();
				Iterator it = nameElts.iterator();
				while (it.hasNext()){
				   String name = (String) it.next(); 
				   Element elt = new Element("mmmElement");
				   elt.setAttribute("name", name);
				   ArrayList<Operation> valeur = elts.get(name); 
				   for (int i=0;i<valeur.size();i++){
					   Element op = new Element("operation");
					   op.setAttribute("op", valeur.get(i)+"");
					   elt.addContent(op);
				   }
				   newFragment.addContent(elt);
				}
				//relationships
				HashMap<String, ArrayList<Operation>> rels= new HashMap<String, ArrayList<Operation>>();
				rels.putAll(fgt.getRelationshipList());
				Set nameRels = rels.keySet();
				it = nameRels.iterator();
				while (it.hasNext()){
				   String name = (String) it.next(); 
				   Element rel = new Element("mmmRelationship");
				   rel.setAttribute("name", name);
				   ArrayList<Operation> valeur = rels.get(name); 
				   for (int i=0;i<valeur.size();i++){
					   Element op = new Element("operation");
					   op.setAttribute("op", valeur.get(i)+"");
					   rel.addContent(op);
				   }
				   newFragment.addContent(rel);
				}
				
				root.addContent(newFragment);
				
				//save new tree in the file
				XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
				sortie.output(document, new FileOutputStream(fileName));
				
			} catch (JDOMException e) {
				JOptionPane.showMessageDialog(null,e.getMessage(),
	                    "File error", JOptionPane.ERROR_MESSAGE);
	            System.exit(1);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, "XML-file not found",
	                    "File error", JOptionPane.ERROR_MESSAGE);
	            System.exit(1);
			}
		
	}
	
	
	public void addOperation(Fragment f, String comp, Operation op){
		try {
			document = builder.build(fileName);
			root = document.getRootElement();
			List fgts = root.getChildren("fragment");
			Iterator it = fgts.iterator();
			
			while(it.hasNext()){
				Element current = (Element)it.next();
				//System.out.println("current : "+current.getAttribute("name")+" "+f.getName()+" ");
				if(current.getAttribute("name").getValue().equals(f.getName()) &&
						current.getAttribute("process").getValue().equals(f.getProcess())){
					List comps = current.getChildren("mmmElement");
					Iterator itc = comps.iterator();
					while(itc.hasNext()){
						Element currentcomp = (Element)itc.next();
						//System.out.println("currentcomp : "+currentcomp.getAttribute("name")+" "+comp+" ");
						if(currentcomp.getAttribute("name").getValue().equals(comp)){
							Element ope = new Element("operation");
							   ope.setAttribute("op", op+"");
							   currentcomp.addContent(ope);
							   //System.out.println("op ajouter");
						}
					}
					
					comps = current.getChildren("mmmRelationship");
					itc = comps.iterator();
					while(itc.hasNext()){
						Element currentcomp = (Element)itc.next();
						//System.out.println("currentcomp : "+currentcomp.getAttribute("name")+" "+comp+" ");
						if(currentcomp.getAttribute("name").getValue().equals(comp)){
							Element ope = new Element("operation");
							   ope.setAttribute("op", op+"");
							   currentcomp.addContent(ope);
							   //System.out.println("op ajouter");
						}
					}
					//System.out.println("comp modifier");
					
				}
			}
			
			XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
			sortie.output(document, new FileOutputStream(fileName));
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	public void removeFragment(Fragment f){
		try {
			document = builder.build(fileName);
			root = document.getRootElement();
			List fgts = root.getChildren("fragment");
			Iterator it = fgts.iterator();
			boolean flag=it.hasNext();
			while(flag){
				boolean notremove = true;
				Element current = (Element)it.next();
				//System.out.println("current : "+current.getAttribute("name")+" "+f.getName()+" ");
				if(current.getAttribute("name").getValue().equals(f.getName()) &&
						current.getAttribute("process").getValue().equals(f.getProcess())){
					root.removeContent(current);
					notremove=false;
					//System.out.println("remove done");
				}
				if(notremove){
					flag=it.hasNext();
				}
				else{
					flag=false;
				}
			}
			
			XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
			sortie.output(document, new FileOutputStream(fileName));
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setPosition(Fragment f, String newPosition){
		try {
			document = builder.build(fileName);
			root = document.getRootElement();
			List fgts = root.getChildren("fragment");
			Iterator it = fgts.iterator();
			
			while(it.hasNext()){
				Element current = (Element)it.next();
				//System.out.println("current : "+current.getAttribute("name")+" "+f.getName()+" ");
				if(current.getAttribute("name").getValue().equals(f.getName()) &&
						current.getAttribute("process").getValue().equals(f.getProcess())){
					current.setAttribute("position", newPosition);
				}
			}
			XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
			sortie.output(document, new FileOutputStream(fileName));
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
}
